package com.ztc.common;

import java.net.ConnectException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.log4j.Logger;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.mysql.jdbc.CommunicationsException;

/**
 * @类名：GlobalExceptionHandler.java
 * @作者：李晓平
 * @时间：2018年8月16日 下午2:45:30
 * @描述：全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class})
public class GlobalExceptionHandler {
	private Logger logger = Logger.getLogger(GlobalExceptionHandler.class);
	
    /**
     * 系统异常处理
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map<String, Object> defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String message = "";
        if(e instanceof CommunicationsException || e instanceof CannotCreateTransactionException
				|| e instanceof CannotGetJdbcConnectionException || e instanceof ConnectException
				|| e instanceof PersistenceException || e instanceof MyBatisSystemException) {
			message = "数据库连接异常，请联系管理员或者再次尝试";
		} else if(e instanceof SQLException) {
			message = "数据库操作异常";
		} else if (e instanceof NullPointerException || e instanceof IndexOutOfBoundsException
				|| e instanceof ClassCastException || e instanceof NumberFormatException) {
			message = "执行异常";
		} else if(e instanceof IllegalArgumentException) {
        	message = e.getMessage();
        } else {
			message = "操作失败";
		}
        logger.error(message, e);
        resultMap.put("success", false);
		resultMap.put("message", message);
        return resultMap;
    }
}
